package org.miniframework.mvc.processor.impl;

import lombok.extern.slf4j.Slf4j;
import org.miniframework.mvc.RequestProcessorChain;
import org.miniframework.mvc.processor.RequestProcessor;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;

/**
 * jsp资源请求处理，规定jsp需要放在templates目录下才能使用
 */
@Slf4j
public class JspRequestProcessor implements RequestProcessor {

    public static final String JSP_SERVLET = "jsp";
    public static final String JSP_PREFIX_TEMPLATES = "/templates";
    //tomcat默认请求派发器RequestDispatcher的名称
    private RequestDispatcher jspServlet;

    public JspRequestProcessor(ServletContext servletContext){
        this.jspServlet = servletContext.getNamedDispatcher(JSP_SERVLET);
        if (this.jspServlet == null){
            throw new RuntimeException(" there is no JSP_SERVLET");
        }
        log.info("The default servlet for jsp resource is {}", JSP_SERVLET);
    }

    /**
     * 处理jsp请求 ,请求形式 /templates/../*.jsp
     * @param chain 调用链,用于结果处理参数的组装,以及处理时必要的参数信息传递
     * @return 如果已经处理返回false, 没有处理返回true, 让下一个请求处理器进行处理
     * @throws Exception
     */
    @Override
    public boolean process(RequestProcessorChain chain) throws Exception {
        // 看是否为jsp 是,进行处理,不是则返回true
        if (isJsp(chain.getRequestPath())){
            jspServlet.forward(chain.getRequest(),chain.getResponse());
            return false;
        }
        return true;
    }

    public boolean isJsp(String path){
        return path.startsWith(JSP_PREFIX_TEMPLATES);
    }
}
